package com.xiaozhengkeji.springboot.frame.easy.security;

import com.alibaba.fastjson.JSON;
import com.xiaozhengkeji.springboot.frame.easy.entity.SysUser;
import com.xiaozhengkeji.springboot.frame.easy.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户验证方法
 *
 * @author xiaozheng
 * Created on 2020/8/15 9:20.
 */
@Component
@Primary
@Slf4j
public class JwtUserDetailsServiceImpl implements UserDetailsService {
    private SysUserService userService;

    @Autowired
    public JwtUserDetailsServiceImpl(SysUserService userService) {
        log.info("JwtUserDetailsServiceImpl->INIT");
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser quUser = new SysUser();
        quUser.setUsername(username);
        SysUser user = userService.queryAll(quUser).get(0);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
            List<String> Roles = new LinkedList<>();
            if (!user.getUserRole().equalsIgnoreCase("ROLE_def")) {
                Roles.add("ROLE_def");
            }
            Roles.add(user.getUserRole());
            return new JwtUser(user.getUsername(), user.getPassword(), Roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        }
    }

}
